<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\common\ArrayHelper;
use app\models\TCourseMember;
use app\models\TCourseInfo;
use app\models\TCourseEvaluate;
use Faker\Provider\Uuid;

class CourseController extends Controller{
    public $enableCsrfValidation = false;
    public function init()
    {
        parent::init();
        header('Access-Control-Allow-Origin: *');
    }
    /*
     * 获取联盟下的课程
     * create_by:gyq
     * create_time:2019/12/25
     * */
    public function actionGetCourseList(){
            $error = array();
            $pageIndex = !empty($_REQUEST['pageIndex'])?$_REQUEST['pageIndex']:'1';
            $pageSize = !empty($_REQUEST['pageSize'])?$_REQUEST['pageSize']:'10';
            $projectId = !empty($_REQUEST['projectId'])?$_REQUEST['projectId']:6;//默认18 测试为6
            $keyword = isset($_REQUEST['keyword'])&&!empty($_REQUEST['keyword'])?$_REQUEST['keyword']:'';
            $limit=$pageSize*($pageIndex-1);
            if(!empty($error))
            {
                $result=[
                    "state"=>true,
                    "code"=>200,
                    "message"=>"缺少请求参数",
                    "data"=>['联盟ID不能为空']
                ];
                \yii::$app->end(json_encode($result));
            }
            $where = '';
            if(!empty($keyword))
            {
                $keyword=str_replace("'","''",$keyword);
                $where .= " AND (tci.name like '%".$keyword."%' OR sci.pet_name like '%".$keyword."%')";
            }
            $where.=" order by sci.create_time desc";
            $sql="SELECT
	sci.t_course_id,
	sci.b_course_id,
	tci.create_by as create_by,
	tci.name as course_name,
	tci.image_url,
	sci.create_time,
	sci.pet_name,
	sci.people_num,
	sci.comment_num
FROM
	`static_course_info` sci
LEFT JOIN t_course_info tci ON tci.id = sci.t_course_id
WHERE
	tci.course_visibility = 'courseVisibility.public'
AND tci.course_status = 'courseCheckStatus.release'
AND (
	tci.group_id <> '49812a3e-aec4-11e9-9997-525400c3827b'
	OR tci.group_id IS NULL
)
AND tci.project_id =:projectId
AND tci.del_flag = 0  ";
                    $openCourseList=\yii::$app->db->createCommand($sql)->bindValues([':projectId'=>$projectId])->queryAll();
                    $totalNum=count($openCourseList);//全部课程总数目
                    //课程分页
                    $sql.=$where." LIMIT ".$limit.",".$pageSize;
                    $courseList=\yii::$app->db->createCommand($sql)->bindValues([':projectId'=>$projectId])->queryAll();
                    //处理课程封面问题
                    foreach ($courseList as $key=>&$value){
                        if(!empty($value['image_url'])){
                            $value['image_url']=\yii::$app->params['fileUrlWeiXin'].$value['image_url'];
                        }
                    }
                    //处理课程时间
                    foreach($courseList as $key=>&$value){
                        $value['create_time']=substr($value['create_time'],0,10);
                    }
                    //处理作者所属学校问题
                    foreach($courseList as $key=>&$value){
                        $sql="SELECT
	s.school_name
FROM
	t_base_school s
LEFT JOIN t_base_user_profile p ON p.school_id = s.id
WHERE
	s.del_flag = 0
AND p.del_flag = 0
AND p.user_id =:create_by";
                        $value['school_name']=\yii::$app->db->createCommand($sql)->bindValues([':create_by'=>$value['create_by']])->queryScalar();
                    }
                    $result=[
                        "state"=>true,
                        "code"=>200,
                        "message"=>"",
                        "data"=>[
                            "totalCount"=>(int)$totalNum,
                            "courseList"=>$courseList
                        ]
                    ];
                    \yii::$app->end(json_encode($result));
    }
    /**
     * 微信小程序课程大纲接口
     * @param int courseId:课程ID userId：用户ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-25
     * @author: gyq
     */
    public function actionAppGetCourseOutline(){
        $error = array();
        $courseId = !empty($_REQUEST['courseId'])?$_REQUEST['courseId']:$error=array('课程ID不能为空');
        $userId = !empty($_REQUEST['userId'])?$_REQUEST['userId']:'';
        if(!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }else{
            $sql = "SELECT
	a.id,
	a.name,
	a.content,
	a.total_hour,
	a.image_url,
	p.pet_name,
	s.school_name
FROM
	t_course_info a
LEFT JOIN t_base_user_profile p ON p.user_id = a.create_by
LEFT JOIN t_base_school s ON s.id = p.school_id
WHERE
	a.id =:courseId";
            $courseInfo = Yii::$app->db->createCommand($sql)->bindValue(':courseId',$courseId)->queryOne();
            if(!empty($courseInfo)){
                $t_num = \app\models\TCourseTeacher::find()->select('distinct teacher_id')->where('course_id=:courseId and del_flag=0',[':courseId'=>$courseId])->count();
                $s_num = TCourseMember::find()->select('distinct user_id')->where('course_id=:courseId and del_flag=0',[':courseId'=>$courseId])->count();
                $courseInfo['content'] = str_replace('&nbsp;', '', strip_tags(htmlspecialchars_decode($courseInfo['content'])));
                $courseInfo['teacher_num'] = $t_num;//教师数量
                $courseInfo['student_num'] = $s_num;//学生数量
                //查询课程大纲
                $sql="select content from t_course_outline_file where del_flag=0 and t_course_id=:courseId";
                $outline=\yii::$app->db->createCommand($sql)->bindValues([':courseId'=>$courseId])->queryScalar();
                //替换课程大纲内部的http
                $outline=str_replace('?furl=http://viewfile.test4.36ve.com','?ssl=1&furl=https://viewfiletest4.36ve.com',$outline);
                $courseInfo['outline'] = empty($outline) ? "" : $outline;//课程大纲
                //课程报名状态
                $join = TCourseMember::find()->select('id')->where('course_id=:courseId and user_id=:userId and del_flag=0',[':courseId' => $courseId,':userId' => $userId])->one();
                if($join)
                {
                    $courseInfo['joinCourseStatus'] = 'yesOrNo.yes';
                }
                else
                {
                    $courseInfo['joinCourseStatus'] = 'yesOrNo.no';
                }
                //处理课程封面前缀
                if(!empty($courseInfo['image_url'])){
                    $courseInfo['image_url']=\yii::$app->params['fileUrlWeiXin'].$courseInfo['image_url'];
                }
                $result = [
                    'msg' => '查询成功',
                    'ver' => '1.5.0',
                    'data' => $courseInfo,
                    'code' => '200'
                ];
            }else{
                $result = [
                    'msg' => '暂无内容',
                    'ver' => '1.5.0',
                    'data' => ['暂无内容'],
                    'code' => '404'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序加入课程接口
     * @param int  courseId:课程ID userId:用户ID  projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-25
     * @author: gyq
     */
    public function actionAppJoinCourse()
    {
        set_time_limit(0);
        $error = array();
        $courseId = !empty($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $userId = !empty($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $projectId = !empty($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $course = TCourseInfo::findOne($courseId);
            if($course->allowed_join=='yesOrNo.no')
            {
                $result = [
                    'msg' => '此课程不允许加入',
                    'ver' => '1.5.0',
                    'data' => ['此课程不允许加入'],
                    'success' => false,
                    'code' => '401'
                ];
                Yii::$app->end(json_encode($result));
            }
            $data = TCourseMember::find()->where('user_id=:userId and course_id=:courseId and del_flag=0', [':userId' => $userId, ':courseId' => $courseId])->one();
            if(!empty($data))
            {
                $result = [
                    'msg' => '已加入',
                    'ver' => '1.5.0',
                    'data' => ['已加入'],
                    'success' => false,
                    'code' => '603'
                ];
                Yii::$app->end(json_encode($result));
            }
            $model = new TCourseMember();
            $uuid = Uuid::uuid();
            $model->id = $uuid;
            $model->user_id = $userId;
            $model->class_id = '-1';
            $model->course_id = $courseId;
            $model->create_by = $userId;
            $model->create_time = date("Y-m-d H:i:s",time());
            $model->del_flag = 0;
            $model->old_id = $uuid;
            if($model->validate() && $model->save())
            {
//                $time = date("Y-m-d H:i:s");
                $sql = "SELECT tbu.id,tbu.project_id,tbu.old_id, tbup.type, tbup.school_id,tbup.province, tbup.major_id, tbup.birthday, tbup.gender, tbup.mobilephone, tbu.username, tbup.pet_name, tbup.student_no, tbup.city, tbup.email FROM t_base_user tbu "
                    . "LEFT JOIN t_base_user_profile tbup ON tbu.id = tbup.user_id "
                    . "WHERE tbu.del_flag = 0 AND tbu.id = :user_id AND tbup.del_flag = 0";
                $userInfo = \app\models\TBaseUser::findBySql($sql,[':user_id'=>$userId])->asArray()->one();
                if($userInfo['project_id'] != $projectId){
                    $userMultipleProject = \app\models\TBaseUserToMultipleProject::findOne(['user_id'=>$userId,'self_project_id'=>$userInfo['project_id'],'enter_project_id'=>$projectId,'role_type'=>$userInfo['type'],'del_flag'=>0]);
                    if(empty($userMultipleProject)){
                        $MultipleProject = new \app\models\TBaseUserToMultipleProject();
                        $uuid = Uuid::uuid();
                        $MultipleProject->id = $uuid;
                        $MultipleProject->user_id = $userId;
                        $MultipleProject->self_project_id = $userInfo['project_id'];
                        $MultipleProject->enter_project_id = $projectId;
                        $MultipleProject->role_type = $userInfo['type'];
                        $MultipleProject->del_flag = 0;
                        if($MultipleProject->save()){
//                            switch ($userInfo['type']) {
//                                case 'userType.teacher':
//                                    $role_type = '教师';
//                                    break;
//                                case 'userType.student':
//                                    $role_type = '学生';
//                                    break;
//                                case 'userType.society':
//                                    $role_type = '社会学习者';
//                                    break;
//                                case 'userType.company':
//                                    $role_type = '企业用户';
//                                    break;
//                                default:
//                                    $role_type = '学生';
//                                    break;
//                            }
//                            $userImport = [
//                                'userid' => $userInfo['old_id'],
//                                'birthday' => substr($userInfo['birthday'], 0, 10),
//                                'city' => $userInfo['city'],
//                                'email' => $userInfo['email'],
//                                'gender' => $userInfo['gender']=='gender.male'?'男':'女',
//                                'institute' => empty(\app\models\User::getSchoolInfo($userInfo['school_id'])->school_name) ? '' : \app\models\User::getSchoolInfo($userInfo['school_id'])->school_name,
//                                'province' => $userInfo['province'],
//                                'role' => $role_type,
//                                'specialty' => empty(\app\models\User::getMajorInfo($userInfo['major_id'])->name) ? '' : \app\models\User::getMajorInfo($userInfo['major_id'])->name,
//                                'telephone' => $userInfo['mobilephone'],
//                                'username' => $userInfo['username'],
//                                'realname' => $userInfo['pet_name'],
//                                'enrollmentnum' => $userInfo['student_no'],
//                                'createdtime' => $time,
//                                'modifiedtime' => $time,
//                            ];
//                            @PdUtils::SaveMongoData($userImport, 'user');
                        }
                    }
                }
//                $s_data=[
//                    'userid' => PdUtils::getOldId('t_base_user', $userId),
//                    'launchcourseid' => PdUtils::getOldId('t_course_info', $courseId),
//                    'status' => '正在学',
//                    'createdtime' => $time,
//                    'modifiedtime' => $time,
//                    'bcourseid' => PdUtils::getOldIdByTid($courseId),
//                    'projectid' => $projectId
//                ];
//                @PdUtils::SaveMongoData($s_data, 'selection-course');
                $result = [
                    'msg' => '加入成功',
                    'ver' => '1.5.0',
                    'data' => ['old_id'=>$model->old_id],
                    'success' => true,
                    'code' => '200'
                ];
            }
            else
            {
                $result = [
                    'msg' => '加入失败',
                    'ver' => '1.5.0',
                    'data' => ['加入失败'],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序获取课程评价接口
     * @param int  courseId:用户ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-26
     * @author: gyq
     */
    public function actionAppGetCourseEvaluation()
    {
        $error = array();
        $courseId = isset($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $evaluate = TCourseEvaluate::find()->select('id,score,content,type,status,object_id,create_by,create_time,old_id')->where('course_id=:courseId and type=:type and del_flag=:del_flag and object_id=:object_id',[':courseId' => $courseId, ':del_flag' => 0, 'type' => 'praiseStudentOrTeacher.student', ':object_id' => $courseId])->asArray()->all();
            if($evaluate)
            {
                $newEvaluate=array();
                foreach ($evaluate as $ev){
                    $sql = "SELECT
								CASE
							WHEN url_image IS NULL THEN
								''
							ELSE
								CONCAT(
									'".Yii::$app->params['fileUrlWeiXin']."',
									url_image
								)
							END AS url_image,
							 pet_name
							FROM
								t_base_user_profile
							WHERE
								user_id='".$ev['create_by']."' AND del_flag=0";
                    $info = \Yii::$app->db->createCommand($sql)->queryOne();
                    if(empty($info['pet_name']))
                    {
                        $sql="select username from t_base_user where id='".$ev['create_by']."'";
                        $username = \Yii::$app->db->createCommand($sql)->queryScalar();
                    }
                    else
                    {
                        $username = $info['pet_name'];
                    }
                    $newEvaluate[]= array_merge($ev,array('url_image'=>$info['url_image'],'username'=>$username,'timestamp'=> strtotime($ev['create_time'])));
                }
                $newEvaluate = $this->array_sort($newEvaluate,'create_time');
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => $newEvaluate,
                    'success' => true,
                    'code' => '200'
                ];
            }elseif(empty($evaluate))
            {
                $result = [
                    'msg' => '没有查询到相关数据',
                    'ver' => '1.5.0',
                    'data' => ['没有查询到相关数据'],
                    'success' => false,
                    'code' => '404'
                ];
            }
            elseif($evaluate===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => ['查找失败'],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    public static function GetDictionaryNameByValue($value){
        $sql="select name from t_sys_dictionary where del_flag=0 and value=:value";
        $result=\yii::$app->db->createCommand($sql)->bindValues([':value'=>$value])->queryScalar();
        if(!empty($result)){
            return $result;
        }
        return "";
    }
    /**
     * 微信小程序保存课程评价接口
     * @param int  courseId:用户ID  projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-26
     * @author: gyq
     */
    public function actionAppSaveCourseEvaluate()
    {
        $error = array();
        $courseId = isset($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $score = isset($_REQUEST['score'])?$_REQUEST['score']:$error[]=array('评价分数不能为空');
        $content = isset($_REQUEST['content'])?$_REQUEST['content']:$error[]=array('评价内容不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $evaluate = new TCourseEvaluate();
            $uuid = Uuid::uuid();
            $evaluate->attributes = $_REQUEST;
            $evaluate->id = $uuid;
            $evaluate->score = $score;
            $evaluate->type = 'praiseStudentOrTeacher.student';
            $evaluate->content = $content;
            $evaluate->course_id = $courseId;
            $evaluate->object_id = $courseId;
            $evaluate->create_by = $userId;
            $evaluate->create_time = date("Y-m-d H:i:s",time());
            $evaluate->del_flag = 0;
            $evaluate->old_id = $uuid;
            if($evaluate->validate() && $evaluate->save())
            {
                $result = [
                    'msg' => '保存成功',
                    'ver' => '1.5.0',
                    'data' => ['保存成功'],
                    'success' => true,
                    'code' => '200'
                ];
            }
            else
            {
                $result = [
                    'msg' => '保存失败',
                    'ver' => '1.5.0',
                    'data' => ['保存失败'],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 查询报名状态
     * @param int  courseId:用户ID  projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2019-12-30
     * @author: gyq
     */
    public function actionGetJoinStatus()
    {
        $error = array();
        $courseId = isset($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:'';
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:'';
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
                $join = TCourseMember::find()->select('id')->where('course_id=:courseId and user_id=:userId and del_flag=0',[':courseId' => $courseId,':userId' => $userId])->one();
                if($join)
                {
                    $status = 'yesOrNo.yes';
                }
                else
                {
                    $status = 'yesOrNo.no';
                }
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => [
                        'status' => $status
                    ],
                    'success' => true,
                    'code' => '200'
                ];
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 微信小程序我的课程列表接口
     * @param int  userId:用户ID  projectId:联盟ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-01-07
     * @author: gyq
     */
    public function actionAppGetMyCoursePageList()
    {
        $error = array();
        $userId = isset($_REQUEST['userId'])?$_REQUEST['userId']:$error[]=array('用户ID不能为空');
        $projectId = isset($_REQUEST['projectId'])?$_REQUEST['projectId']:$error[]=array('联盟ID不能为空');
        $keyword = isset($_REQUEST['keyword'])&&!empty($_REQUEST['keyword'])?$_REQUEST['keyword']:'';
        $pageSize = isset($_REQUEST['pageSize'])?$_REQUEST['pageSize']:'20';
        $page = isset($_REQUEST['pageIndex'])?$_REQUEST['pageIndex']:'1';
        $limit = "limit ".($page-1)*$pageSize.",$pageSize";
        if(!empty($error))
        {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }
        else
        {
            $where="";
            if(!empty($keyword))
            {
                $keyword=str_replace("'","''",$keyword);
                $where .= " AND (c.name like '%".$keyword."%' OR tbup.pet_name like '%".$keyword."%')";
            }
            $sql1 = "SELECT CASE
							WHEN c.image_url='' THEN
			 					''
			 				ELSE
								CONCAT(
			 						'".Yii::$app->params['fileUrlWeiXin']."',
			 						c.image_url
								)
			 				END AS image_url,c.id,c.project_id,c.name,c.b_course_info_id as bcourseId,(SELECT COUNT(DISTINCT m.user_id) FROM t_course_member m WHERE c.id = m.course_id AND m.del_flag=0) AS student_num,c.major_name,c.course_status,c.school_name,tbup.pet_name,(SELECT id FROM t_forum WHERE t_forum.course_id=c.id and del_flag=0) as froum_id,c.old_id as t_old_id FROM t_course_member m LEFT JOIN t_course_info c ON c.id=m.course_id LEFT JOIN t_base_user_profile tbup ON c.create_by=tbup.user_id WHERE m.user_id=:uid AND m.del_flag=0  AND c.del_flag=0 and c.course_status in ('courseCheckStatus.finish','courseCheckStatus.release') ".$where." GROUP BY c.id ORDER BY m.create_time DESC ".$limit."";
            $course = Yii::$app->db->createCommand($sql1)->bindValue(':uid',$userId)->queryAll();
            if($course)
            {
                $course = self::array_is_null($course);
                foreach ($course as $key => $value) {
                    $course[$key]['student_num'] = intval($course[$key]['student_num']);
                    $b_old_id = \app\models\BCourseInfo::find()->select('old_id')->where('id=:bcourseId and del_flag=0',[':bcourseId'=>$value['bcourseId']])->asArray()->one();
                    if($b_old_id){
                        $course[$key]['b_old_id'] = $b_old_id['old_id'];
                    }else{
                        $course[$key]['b_old_id'] = '';
                    }
                }
                $result = [
                    'msg' => '查找成功',
                    'ver' => '1.5.0',
                    'data' => $course,
                    'success' => true,
                    'code' => '200'
                ];
            }
            elseif(empty($course))
            {
                $result = [
                    'msg' => '暂无课程',
                    'ver' => '1.5.0',
                    'data' => [],
                    'success' => false,
                    'code' => '200'
                ];
            }
            elseif($course===false)
            {
                $result = [
                    'msg' => '查找失败',
                    'ver' => '1.5.0',
                    'data' => ['查找失败'],
                    'success' => false,
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * ------------------------------------------
     * 二维数组排序(有键值)
     * @param array $arr 要排序的数据集
     * @param string $keys 指定的键值
     * @param string $type asc正序 desc倒序
     * @return array
     * ------------------------------------------
     */
    public static function array_sort($arr,$keys,$type='desc'){
        $keysvalue = $new_array = array();
        foreach ($arr as $k=>$v){
            $keysvalue[$k] = $v[$keys];
        }
        if($type == 'asc'){
            asort($keysvalue);
        }else{
            arsort($keysvalue);
        }
        reset($keysvalue);
        foreach ($keysvalue as $k=>$v){
            $new_array[] =& $arr[$k];
        }
        return $new_array;
    }
    /**
     * mysql 查询出的数组 null 转 ''
     * @param type $arr
     * @return type
     */
    public static function array_is_null($arr){
        $new_array = array();
        if(count($arr) == count($arr,1)){
            foreach ($arr as $key =>$a){
                $new_array[$key] = $a==NULL?'':$a;
            }
            return $new_array;
        }else{
            foreach ($arr as $key =>$a){
                foreach ($a as $k => $val) {
                    $new_array[$key][$k] = $val==NULL?'':$val;
                }
            }
            return $new_array;
        }
    }
}
?>